/**
 * @function: 通用工具类
 * 包括通用验证函数、日期函数、字符串格式化函数
 * @modify history
 * Date           Author            Description
 * --------------------------------------------------------
 * 2010/01/12     fan.kebin         Created
 *  
 */
package com.byxm.wlgw.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;

@SuppressWarnings("unused")
public class ComUtil {
	private static String[] cSVTCONV;
	private static String[] cJSPCONV;

	private static int UNmaxLength;
	private static int UNminLength;
	private static int PSmaxLength;
	private static int PSminLength;
	
	private static String emailCode;
	private static String chineseCode;
    private static  SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd"); 
	
	static {
		cSVTCONV = new String[]{"'", "\\", "%"};
		cJSPCONV = new String[]{"\\'", "\\\\\\\\", "\\\\%"};
		
		UNmaxLength = 32;
		UNminLength = 2;
		PSmaxLength = 16;
		PSminLength = 3;
		
		emailCode = "^[_0-9a-z-][_.0-9a-z/-]+@([0-9a-z][_0-9a-z.-]+.)+[a-z]{2,3}$";
		chineseCode = "[\\u4E00-\\u9FA5]+";
	}
	
	/******************************** 验证函数 *********************************/
	/**
	 * 验证输入是否为空
	 * 若输入字符串value为空或空字符(包括中文空字符)，那么返回true
	 * 反之返回false
	 * @param value
	 * @return boolean
	 */
	public static boolean isNull(String value) {
		if (value == null || ComUtil.trim(value).length() == 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 判断输入的字符串中均不为空
	 * 若输入的字符串组为空，或者其中包含是空或空字符的字符串，则返回true
	 * 验证通过返回false
	 * @param value
	 * @return
	 */
	public static boolean isHasNull(String... value) {
		if(value != null && value.length > 0) {
			for(int i = 0; i < value.length; i++) {
				if(ComUtil.isNull(value[i])) {
					return true;
				}
			}
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * 长度验证，验证长度是否在规定的范围内
	 * 若value为空或空字符，返回false
	 * 若min > max，返回false
	 * 若value的length范围不在min和max之间，返回false
	 * @return
	 */
	public static boolean isSupportLength(String value, int min, int max) {
		if(ComUtil.isNull(value)) {
			return false;
		} else if(max < min) {
			return false;
		}
		
		int len = getLength(value);
		if(len > max || len < min) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * 长度验证
	 * 验证长度是否超出规定的长度
	 * @param value
	 * @param len
	 * @return 
	 */
	public static boolean isOutOfLength(String value, int len) {
		if (ComUtil.isNull(value)) {
			return true;
		} else if (getLength(value) > len) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 长度验证
	 * 验证长度是否小于规定的长度
	 * @param value
	 * @param len
	 * @return
	 */
	public static boolean isLessOfLength(String value, int len) {
		if (ComUtil.isNull(value)) {
			return true;
		} else if (getLength(value) < len) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 取得字串长度
	 * @param value
	 * @return 
	 */
	public static int getLength(String value) {
		if(value == null) {
			return -1;
		} else {
			return value.trim().getBytes().length;
		}
	}
	
	/**
	 * 数值长度验证
	 * 若被验证的字符串不能转换成数值类型，那么返回true
	 * 若被验证的字符串超过len长度，那么返回true
	 * 验证通过返回false
	 * @param value 需要被验证的字符串
	 * @param len 被验证字符串转换成数值类型后不能超过的长度
	 * @return 验证通过返回false，反之返回true
	 */
	public static boolean isOutOfLengthNum(String value, int len) {
		if (!ComUtil.isNum(2, value)) {
			return true;
		}

		String nval = value.replaceAll("[,]", "");
		nval = nval.replaceAll("[.]", "");
		nval = nval.replaceAll("[-]", "");
		
		if (getLength(nval) > len) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 数值验证
	 * @param flg 0: 正整数；1：非负数；2：所有
	 * @param value
	 * @return 
	 */
	public static boolean isNum(int flg, String value) {
		try {
			if (value == null || getLength(value) == 0) {
				return false;
			} else if(flg == 2) {
				value = value.replaceAll("[-]", "");
			} else if(flg == 0 && value.startsWith("0")) {
				return false;
			}
			
			value = value.replaceAll("[,]", "");
			byte[] b = value.trim().getBytes();

			for(int i = 0; i < b.length; i++) {
				if(!ascallnum(b[i])) {
					return false;
				}
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 实数验证（带小数位数验证）
	 * @param flg 实数范围0: 正整数；1：非负数；2：所有
	 * @param value 需要被验证的值
	 * @param p_len 小数位最大长度
	 * @return 若value为空或空字符，或者不满足条件，均返回false
	 */
	public static boolean isPer(int flg, String value, int p_len) {
		if(ComUtil.isNull(value)) {
			return false;
		}
		
		if(value.contains(".")) {
			String[] value2 = value.split("\\.");
			if(value2.length != 2 || (!isNum(flg, value2[0].trim()))
					|| (!isNum(1, value2[1].trim()))
					|| (p_len > 0 && getLength(value2[1].trim()) > p_len)) {
				return false;
			}
		} else if(!isNum(flg, value)) {
			return false;
		}
		return true;
	}

	/**
	 * 日期验证，仅判断年月
	 * @param year
	 * @param month
	 * @return
	 */
	public static boolean isDate(String year, String month) {
		return isDate(year, month, "1");
	}
	
	/**
	 * 日期验证
	 * @param year
	 * @param month
	 * @param day
	 * @return
	 */
	public static boolean isDate(String year, String month, String day) {
		try {
			if (ComUtil.isHasNull(year, month, day)) {
				return false;
			} else if (Integer.parseInt(year) == 0) {
				return false;
			}

			GregorianCalendar cal = new GregorianCalendar();
			cal.setLenient(false);
			cal.clear();
			cal.set(Integer.parseInt(year), 
					Integer.parseInt(month) - 1,
					Integer.parseInt(day));
			Date date = cal.getTime();

			return true;

		} catch (IllegalArgumentException e) {
			return false;
		} catch (Exception e) {
			return false;
		}
	}
	
	/**
	 * 时间验证
	 * @param hour
	 * @param minute
	 * @return boolean
	 */
	public static boolean isTime(String hour, String minute) {
		try {
			if (ComUtil.isHasNull(hour, minute) 
					|| !isNum(1, hour.trim()) 
					|| !isNum(1, minute.trim())) {
				return false;
			}

			int n_hour = Integer.parseInt(hour.trim());
			int n_minute = Integer.parseInt(minute.trim());
			
			if (n_hour < 0 || n_hour > 23 || n_minute < 0 || n_minute > 59) {
				return false;
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 日期月的判断
	 * @param month
	 * @return
	 */
	public static boolean isMonth(String month) {
		try {
			if (ComUtil.isNull(month) || !ComUtil.isNum(1, month.trim())) {
				return false;
			}

			int n_month = Integer.parseInt(month.trim());
			if (n_month < 0 || n_month > 12) {
				return false;
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 日期日的判断
	 * @param day
	 * @return
	 */
	public static boolean isDay(String day) {
		try {
			if (ComUtil.isNull(day) || !ComUtil.isNum(1, day.trim())) {
				return false;
			}

			int n_day = Integer.parseInt(day.trim());
			if (n_day < 0 || n_day > 31) {
				return false;
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 电话号码验证
	 * @param value
	 * @param len
	 * @return
	 */
	public static boolean isTelNo(String value, int len) {
		if (ComUtil.isNull(value)) {
			return false;
		}
		
		if (!ComUtil.isNum(1, value) || ComUtil.getLength(value) != len) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 邮政编码验证
	 * @param value
	 * @return
	 */
	public static boolean isZip(String value) {
		if (ComUtil.isNull(value) || getLength(value) != 6 || !isNum(1, value)) {
			return false;
		}
		return true;
	}

	/**
	 * 电子邮件地址验证
	 * @param value
	 * @return
	 */
	public static boolean isEmailAddress(String value) {
		if (ComUtil.isNull(value) || !value.trim().matches(emailCode)) {
			return false;
		}
		return true;
	}

	/**
	 * 判断中文字符
	 * @param value
	 * @return
	 */
	public static boolean isChineseChar(String value) {
		if(ComUtil.isNull(value) || !value.matches(chineseCode)) {
			return false;
		} else {
			return true;
		}
//		try {
//			if (ComUtil.isNull(value)) {
//				return false;
//			}
//			char[] chars = value.toCharArray();
//			for (int i = 0; i < chars.length; i++) {
//				String target = String.valueOf(chars[i]);
//				byte[] b = target.getBytes();
//				if (b.length == 2) {
//				} else {
//					return false;
//				}
//			}
//			return true;
//		} catch (Exception e) {
//			return false;
//		}
	}

	/**
	 * 过去日期判断
	 * @param year
	 * @param month
	 * @param day
	 * @return boolean
	 */
	public static boolean isPastDate(String year, String month, String day) {
		try {
			GregorianCalendar cal = new GregorianCalendar();
			cal.setLenient(false);
			SimpleDateFormat fmDate = new SimpleDateFormat("yyyyMMdd");
			String today = fmDate.format(cal.getTime());
			cal.clear();
			cal.set(Integer.parseInt(year), Integer.parseInt(month) - 1,
					Integer.parseInt(day));
			String inputday = fmDate.format(cal.getTime());

			if (inputday.compareTo(today) < 0) {
				return true;
			} else {
				return false;
			}
		} catch (IllegalArgumentException e) {
			return false;
		}
	}

	/**
	 * 判断是否包含（",;,'）等字符
	 * @param value
	 * @return
	 */
	public static boolean hasInvalidCharactor(String value) {
		if(value == null) {
			return false;
		} else if(value.contains(";") || value.contains("'") || value.contains("\"")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 英数判断
	 * @param value
	 * @return
	 */
	public static boolean isAlphabetOrNumeric(String value) {
		try {
			byte[] b = value.getBytes();

			for (int i = 0; i < b.length; i++) {
				if (ascnum(b[i]) == false)
					return false;
			}

			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 数字、字母、特殊字符验证
	 * @param value
	 * @return 
	 */
	public static boolean isAlphabetOrNumericOrSymbol(String value) {
		try {
			byte[] b = value.getBytes();
			if(b.length > value.length()) {
				return false;
			}
			
			for (int i = 0; i < b.length; i++) {
				if (!ascnumcode(b[i])) {
					return false;
				}
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/******************************** 日期函数 *********************************/
	/**
	 * 修改月份
	 */
	@SuppressWarnings("deprecation")
	public static String changeDateAsMonth(String date, int imonth) {
		GregorianCalendar calendar = new GregorianCalendar();
		if (date.length() == 8) {
			calendar.set(Integer.parseInt(date.substring(0, 4)), Integer
					.parseInt(date.substring(4, 6)) - 1, Integer.parseInt(date
					.substring(6, 8)));
		} else if (date.length() == 10) {
			calendar.set(Integer.parseInt(date.substring(0, 4)), Integer
					.parseInt(date.substring(5, 7)) - 1, Integer.parseInt(date
					.substring(8, 10)));
		}
		calendar.add(GregorianCalendar.MONTH, imonth);
		String sDate[] = calendar.getTime().toLocaleString().split(" ");
		return sDate[0];
	}

	/**
	 * 日期比较
	 * 
	 */
	public static int compareDate(String aDate, String bDate) {

		String[] strDate;
		GregorianCalendar aCal = new GregorianCalendar();
		GregorianCalendar bCal = new GregorianCalendar();
		if (aDate.indexOf("/") != -1) {
			strDate = aDate.split("/");
			aCal.set(Integer.parseInt(strDate[0].trim()), Integer
					.parseInt(strDate[1].trim()) - 1, Integer
					.parseInt(strDate[2].trim()));
		} else if (aDate.indexOf("-") != -1) {
			strDate = aDate.split("-");
			aCal.set(Integer.parseInt(strDate[0].trim()), Integer
					.parseInt(strDate[1].trim()) - 1, Integer
					.parseInt(strDate[2].trim()));
		} else if (aDate.length() == 8) {
			aCal.set(Integer.parseInt(aDate.substring(0, 4)), Integer
					.parseInt(aDate.substring(4, 6)) - 1, Integer
					.parseInt(aDate.substring(6, 8)));
		} else if (aDate.length() == 10) {
			aCal.set(Integer.parseInt(aDate.substring(0, 4)), Integer
					.parseInt(aDate.substring(5, 7)) - 1, Integer
					.parseInt(aDate.substring(8, 10)));
		}

		if (bDate.indexOf("/") != -1) {
			strDate = bDate.split("/");
			bCal.set(Integer.parseInt(strDate[0].trim()), Integer
					.parseInt(strDate[1].trim()) - 1, Integer
					.parseInt(strDate[2].trim()));
		} else if (bDate.indexOf("-") != -1) {
			strDate = bDate.split("-");
			bCal.set(Integer.parseInt(strDate[0].trim()), Integer
					.parseInt(strDate[1].trim()) - 1, Integer
					.parseInt(strDate[2].trim()));
		} else if (bDate.length() == 8) {
			bCal.set(Integer.parseInt(bDate.substring(0, 4)), Integer
					.parseInt(bDate.substring(4, 6)) - 1, Integer
					.parseInt(bDate.substring(6, 8)));
		} else if (bDate.length() == 10) {
			bCal.set(Integer.parseInt(bDate.substring(0, 4)), Integer
					.parseInt(bDate.substring(5, 7)) - 1, Integer
					.parseInt(bDate.substring(8, 10)));
		}

		return aCal.compareTo(bCal);
	}

	/**
	 * 闰年判断
	 * @param year
	 * @return
	 */
	public static boolean isLeapYear(String year) {
		try {
			int intyear = Integer.parseInt(year);
			if (intyear % 400 == 0 || (intyear % 4 == 0 && intyear % 100 != 0)) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 计算年龄
	 * @param birthday
	 * @return
	 */
	public static String getAge(String birthday) {
		SimpleDateFormat fm = new SimpleDateFormat("yyyyMMdd");
		String strNowDate = fm.format(new java.util.Date());
		String age = new String();
		age = String.valueOf((Integer.parseInt(strNowDate) - Integer
				.parseInt(birthday)) / 10000);
		return age;
	}

	/**
	 * 取当前日期
	 * @param format
	 * @throws Exception
	 * @return String
	 */
	public static String getDate(String format) throws Exception {
		SimpleDateFormat fm = new SimpleDateFormat(format);
		return fm.format(new java.util.Date());
	}

	/**
	 * 取得指定年月的天数
	 * @param year
	 * @param month
	 * @return
	 */
	public static int getMonthDay(String year, String month) {
		int iRet = 0;
		switch (Integer.parseInt(month)) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			iRet = 31;
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			iRet = 30;
			break;
		case 2:
			iRet = isLeapYear(year) == true ? 28 : 29;
			break;

		}
		return iRet;
	}

	/**
	 * 取得指定日期的星期值
	 * @param year
	 * @param month
	 * @param day
	 * @return
	 */
	public static String weekDay(String year, String month, String day) {
		String strWeekday = "";
		try {
			GregorianCalendar cal = new GregorianCalendar();
			cal.setLenient(false);
			cal.clear();
			cal.set(Integer.parseInt(year), Integer.parseInt(month) - 1,
					Integer.parseInt(day));
			strWeekday = String
					.valueOf(cal.get(java.util.Calendar.DAY_OF_WEEK) - 1);
		} catch (IllegalArgumentException e) {
			strWeekday = "";
		}
		return strWeekday;
	}
	/** 
     * 得到几天前的时间 
     *  
     * @param d 
     * @param day 
     * @return 
     */  
    public  static Date getDateBefore(Date d, int day) {  
        Calendar now = Calendar.getInstance();  
        now.setTime(d);  
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);  
        return now.getTime();  
    } 

	/**
	 * 抓取html中的指定标签的指定属性的值
	 * @param description 给定的html字符串
	 * @param tagName标签名
	 * @param param 属性
	 * @return 图片地址的集合
	 */
	public static List<String> getTagParamValue(String description,String tagName,String param) {

		List<String> list = new ArrayList<String>();
		
		String imgPattern = "<\\s*"+tagName+"\\s+([^>]+)\\s*>";
		Pattern pattern1 = Pattern
				.compile(imgPattern, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern1.matcher(description);

		
		String srcPattern = "\\s*"+param+"\\s*=\\s*\"([^\"]+)\\s*\"";
		Pattern pattern2 = Pattern
				.compile(srcPattern, Pattern.CASE_INSENSITIVE);
		while (matcher.find()) {

			// group()返回符合表达式的内容
			Matcher matcher2 = pattern2.matcher(matcher.group());
			// 一定要find(),这是实际的匹配动作
			if (matcher2.find()) {
				String src = matcher2.group();
				list.add(src.substring(6, src.length() - 1));
			}
		}
		return list;
	}

	/***************************** 字符串格式化函数 *****************************/
	/**
	 * 格式化数值为逗号分隔
	 * @param strValue
	 * @return
	 */
	public static String setComma(String strValue) {
		String sCommaSet = "";
		try {
			String sign;
			StringBuffer sb;
			;
			if (Long.parseLong(strValue) < 0) {
				sign = "-";
				sb = new StringBuffer(Long.toString(Long.parseLong(strValue)
						* -1));
			} else {
				sign = "";
				sb = new StringBuffer(strValue);
			}
			int iLength = sb.length();
			int iCommaCount = (int) ((iLength - 1) / 3); // 逗号总数
			int iCommaPosition = (int) (iLength % 3); // 逗号位置
			if (iCommaPosition == 0) {
				iCommaPosition = 0;
				iCommaPosition = 3;
			}
			if (iCommaCount == 0) {
			}
			for (int i = 0; i < iCommaCount; i++) {
				sb.insert(iCommaPosition + 3 * i + i, ",");
			}
			sCommaSet = sign + sb.toString();

		} catch (NumberFormatException e) {
			sCommaSet = "";
		}
		return sCommaSet;
	}

	/**
	 * 补零至指定长度
	 * @param strvalue
	 * @param length
	 * @return
	 */
	public static String fillZero(String strvalue, int length) {
		StringBuffer s = new StringBuffer();
		for (int i = 0; i < length - strvalue.length(); i++) {
			s.append("0");
		}
		s.append(strvalue);
		return s.toString();
	}

	/**
	 * 设置时间分隔符
	 * @param value
	 * @return
	 */
	public static String setTimeColon(String value) {
		if (value == null) {
			return "";
		} else if (value.length() == 4) {
			return value.substring(0, 2) + ":" + value.substring(2, 4);
		} else if (value.length() == 6) {
			return value.substring(0, 2) + ":" + value.substring(2, 4) + ":"
					+ value.substring(4, 6);
		} else {
			return "";
		}
	}

	/**
	 * 取汉字子串。非汉字字符跳过
	 * @param sContents
	 * @param strLen
	 * @return
	 */
	public static String subChineseContents(String sContents, int strLen) {
		StringBuffer retSubContents = new StringBuffer();
		int iLen = 0;
		for (int i = 0; i < sContents.length(); i++) {
			String sTemp = sContents.substring(i, i + 1);
			if (sTemp.matches(chineseCode)) {
				retSubContents.append(sTemp);
				iLen++;
			}
			if (iLen >= strLen) {
				break;
			}
		}

		return retSubContents.toString();
	}

	/**
	 * 取子串时防止因长度问题取出乱码
	 * @param sContents
	 * @param strLen
	 * @return
	 */
	public static String subContents(String sContents, int strLen) {
		if (isNull(sContents)) {
			sContents = "";
		} else {
			String sOriginContents = new String();
			sOriginContents = sContents;
			if (sContents.length() > strLen) {
				sContents = sContents.substring(0, strLen);

				if (sContents.lastIndexOf("&") != -1) {
					String sTemp = sContents.substring(sContents
							.lastIndexOf("&"), sContents.length());
					if (sTemp.length() < 7) {
						int i = 1;
						while (sContents.lastIndexOf("&") != -1
								&& sTemp.length() < 7) {
							sContents = sOriginContents.substring(0, strLen
									+ i++);
							sTemp = sContents.substring(sContents
									.lastIndexOf("&"), sContents.length());
						}
					}
				}
				sContents = sContents + "...";
			}
		}
		return sContents;
	}

	/**
	 * 删除input字符串中的html格式
	 * @param input
	 * @param length
	 * @return
	 */
	public static String splitAndFilterString(String input, int length) {
		if (input == null || input.trim().equals("")) {
			return "";
		}
		// 去掉所有html元素,
		String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(
				"<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
		int len = str.length();
		if (len <= length) {
			return str;
		} else {
			str = str.substring(0, length);
			str += "......";
		}
		return str;
	}

	/**
	 * 把文本编码为Html代码,由于函数返回
	 */
	public static String htmlEncode(String s) {
		StringBuffer stringbuffer = new StringBuffer();
		int j = s.length();
		for (int i = 0; i < j; i++) {
			char c = s.charAt(i);
			switch (c) {
			case 60:
				stringbuffer.append("&lt;");
				break;
			case 62:
				stringbuffer.append("&gt;");
				break;
			case 38:
				stringbuffer.append("&amp;");
				break;
			case 34:
				stringbuffer.append("&quot;");
				break;
			case 169:
				stringbuffer.append("&copy;");
				break;
			case 174:
				stringbuffer.append("&reg;");
				break;
			case 165:
				stringbuffer.append("&yen;");
				break;
			case 8364:
				stringbuffer.append("&euro;");
				break;
			case 8482:
				stringbuffer.append("&#153;");
				break;
			case 13:
				if (i < j - 1 && s.charAt(i + 1) == 10) {
					stringbuffer.append("<br>");
					i++;
				}
				break;
			case 32:
				if (i < j - 1 && s.charAt(i + 1) == ' ') {
					stringbuffer.append(" &nbsp;");
					i++;
					break;
				}
			default:
				stringbuffer.append(c);
				break;
			}
		}
		return stringbuffer.toString();
	}

	/**
	 * 当输入的内容含有"'"时将它转换为"''"即可查询 
	 * 当输入的内容含有"/"时将它转换为"//"即可查询
	 * 当输入的内容含有"%"时将它转换为"/%"即可查询 	
	 */
	public static String escapeString(String sValue) {
		if(sValue == null) {
			return "";
		}
		if(sValue.contains("'") 
				|| sValue.contains("/")
				|| sValue.contains("%") 
				) {
			StringBuffer str = new StringBuffer();
			for(int i = 0; i < sValue.length(); i++) {
				char ca = sValue.charAt(i);
				switch(ca) {
				case '\'': str.append("''"); break;
				case '/': str.append("//"); break;
				case '%': str.append("/%"); break;				
				default: str.append(ca); break;
				}
			}
			return str.toString();
		}
		return sValue;
	}

	/**
	 * 通用防SQL注入函数java版
	 * 
	 * @param str
	 * @return
	 */
	public static String sql_inj(String str) {
		if (!ComUtil.isNull(str)) {
			return str.replaceAll("'", "''")
					.replaceAll("%27", "''")
					.replaceAll("%", "");
		} else {
			return null;
		}
	}
	
	/**
	 * 匹配sql关键字
	 */
	public static boolean matchSqlKey(String sql) {
		if(sql.contains("select")||sql.contains("update")||sql.contains("insert")) {
			return true;
		}
		else if(sql.contains("or")||sql.contains("and")||sql.contains("like")||sql.contains("=")) {
			return true;
		}
		else if(sql.contains("exec")||sql.contains("from")) {
			return true;
		}
		else {
			return false;
		}
	}

	/**
	 * @Head 转换字符串编码格式
	 * @Deprecated 将字符串转换成指定的编码格式UTF-8
	 * @param sValue 需要转换的字符串
	 * @return 
	 */
	public static String encodeString(String sValue) {
		return encodeString(sValue, "utf-8");
	}
	
	/**
	 * @Head 转换字符串编码格式
	 * @Deprecated 将字符串转换成指定的编码格式，若该编码格式不存在，那么将不予转换
	 * @param sValue 需要转换的字符串
	 * @param encode 转换后的编码方式
	 * @return 指定编码格式的新字符串，若编码格式不存在，那么返回原字符串
	 */
	public static String encodeString(String sValue, String encode) {
		try {
			if(!ComUtil.isNull(encode)) {
				return java.net.URLEncoder.encode(sValue, encode);
			} else {
				return sValue;
			}
		} catch (UnsupportedEncodingException e) {
			return sValue;
		}
	}
	
	
	/********************************* 私有函数 ********************************/
	/**
	 * 数字字符验证
	 * @param byt
	 * @return 
	 */
	private static boolean ascallnum(byte byt) {
		if ((byt < 48) || (byt > 57)) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 数字、字母验证
	 * Asc: 48-57 = '0' -'9'
	 * Asc: 65-90 = 'A' - 'Z'
	 * Asc: 97-122 = 'a' - 'z'
	 * @param byt
	 *            byte
	 * @return boolean
	 */
	private static boolean ascnum(byte byt) {
		if(byt < 48 || (byt > 57 && byt < 65) || (byt > 90 && byt < 97) || byt > 122) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 数字、字母、特殊字符验证
	 * Asc: 33 - 126 but not 34(") and 39(')
	 * @param byt
	 * @return
	 */
	private static boolean ascnumcode(byte byt) {
		if ((byt == 34) || (byt == 39) || (byt < 33) || (byt > 126)) {
			return false;
		} else {
			return true;
		}
	}
	
	private static String trim(String value) {
		return value.replaceAll("[　]", "").trim();
	}
	
    /**
	 * 文件上传
	 * @param filename 上传文件名
	 * @param realPath 上传文件要保存的路径
	 * @param doc 上传文件对象
	 * @return String
	 * @param srcFile 要上传的文件
	 * @param destFile 上传后保存的文件
	 */

	public static String  upload(String filename ,String realPath,File doc){
		int BUFFER_SIZE = 16 * 1024 ;
		String targetFileName  = generateFileName(filename);
		String dir = targetFileName;
		File destFile = new File(realPath);//判断要路径是否存在
		if(!destFile.exists()) {
			destFile.mkdirs();
		}
		File dst = new File(realPath,targetFileName);
		
		try  {   
            InputStream in = null ;   
            OutputStream out = null ;   
            try  {                   
                in = new BufferedInputStream( new FileInputStream(doc), BUFFER_SIZE);   
                out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);   
                byte [] buffer = new byte [BUFFER_SIZE];   
                 while (in.read(buffer) > 0 )  {   
                    out.write(buffer);   
                 }    
             } finally  {   
                if ( null != in)  {   
                   in.close();   
                }    
                if ( null != out)  {   
                   out.close();   
                }    
             }
         } catch (Exception e)  {   
           e.printStackTrace();   
           return null;
        }    
        return dir;
}
	
	/**
     * 抓取html中的图片地址
     * @param description 给定的html字符串
     * @return 图片地址的集合
     * @author 王学成
     */
    public static List<String> getImagesURL(String description) { 

        List<String> list = new ArrayList<String>();
          // img 的正则表达式:匹配<img>标签       
          String imgPattern = "<\\s*img\\s+([^>]+)\\s*>";
          Pattern pattern1 = Pattern.compile(imgPattern, Pattern.CASE_INSENSITIVE);
          Matcher matcher = pattern1.matcher(description); 

          // img src元素的正则表达式：匹配img标签内的src属性
          String srcPattern = "\\s*src\\s*=\\s*\"([^\"]+)\\s*\"";
          Pattern pattern2 = Pattern.compile(srcPattern, Pattern.CASE_INSENSITIVE); 
          while (matcher.find()) {
        	  
             //group()返回符合表达式的内容
              Matcher matcher2 = pattern2 .matcher(matcher.group());
              // 一定要find(),这是实际的匹配动作
              if (matcher2.find()) {
                  String src = matcher2.group();
                	  list.add(src.substring(6, src.length() - 1));
              }
          }
          return list;
      }
    
    
	/**
	 * 用于生成随机字符串，来保存上传文件的文件名
	 * @param fileName 上传文件名
	 */
	private static String generateFileName(String fileName) {    
        DateFormat format = new SimpleDateFormat("yyMMddHHmmss");    
        String formatDate = format.format(new Date());    
        int random        = new Random().nextInt(10000);    
        int position      = fileName.lastIndexOf(".");    
        String extension  = fileName.substring(position);    
            
        return formatDate + random + extension;    
    }
	
	/**
     * 压缩生成上传的图片
     * @param srcJpgFile :要压缩的图片文件
     * @return
     */
    public static String ZipAndReplaceJpg(String srcJpgFile,String destJpgName ) {
    	int imgWidth = 500;
    	int imgHeight= 400;
    	
    	try {
    		srcJpgFile = java.net.URLDecoder.decode(srcJpgFile,"utf-8");
    		java.io.File srcFile = new java.io.File(srcJpgFile);
    		
    		//绝对路径目标文件名    		
    		String destRealJpgName = srcJpgFile.substring(0,srcJpgFile.lastIndexOf("\\")+1) + destJpgName;
			//JPG格式并且文件大于200K须缩小图片尺寸    		
    		if(srcJpgFile.toLowerCase().endsWith(".jpg") && srcFile.length()> 300000 ) {				
				destJpgName = destJpgName + ".jpg";
				destRealJpgName = destRealJpgName  + ".jpg";				
				ZipJpg zipJpg = new ZipJpg(srcJpgFile,destRealJpgName);
				zipJpg.resizeFix(imgWidth, imgHeight);
				//删除原文件
				srcFile.delete();								
			} else {
				//修改图片名称
				destRealJpgName = destRealJpgName + srcFile.getName().substring(srcFile.getName().lastIndexOf("."));
				destJpgName = destJpgName + srcFile.getName().substring(srcFile.getName().lastIndexOf("."));
				srcFile.renameTo(new java.io.File(destRealJpgName));
			}
			
    	} catch(Exception e) {
    		System.out.println(e.toString());
    	}
    	
    	return destJpgName;
		
    }
    
    /**
	 * 日期转成字符
	 */
	public static String dateToStr(Date date) {
		String strDate = dateFm.format(date);
		return strDate;
	}
	/**
	 * 字符转成日期
	 */
	public static Date strToDate(String strDate) {
		Date date = null;
		try {
			date = dateFm.parse(strDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	/**
	 * 将指定文件移动到指定目录下
	 * @return
	 */
	public static String moveFileToDir(String sFile,String destDir,String destFileName) {
		String newFile = null;
		File destFile = new File(destDir); 
		if(!destFile.exists()) {
			synchronized(ComUtil.class) {
				destFile.mkdirs();
			}
			
		}
		File srcFile = new File(sFile);
		if(srcFile.exists()) {
			if(ComUtil.isNull(destFileName) == false) {
				newFile = destDir+"/" +destFileName;				
			} else {				
				newFile = destDir+"/" +srcFile.getName();				
			}
			srcFile.renameTo(new File(newFile));
			//删除原文件
			srcFile.delete();
		} 
		return newFile;
	}
	
	
	
	/**
	 * 把字符串转成UTF-8格式(下载用)
	 * @param str
	 * @return
	 */
	public static String encodeFileName(HttpServletRequest request,HttpServletResponse  response, String cfrfilename) throws UnsupportedEncodingException {   
		String agent =request.getHeader("USER-AGENT");   
		if (null != agent && -1 != agent.indexOf("MSIE"))   
		{   
		String codedfilename = URLEncoder.encode(cfrfilename, "utf-8");   
		response.setContentType("application/x-download");   
		response.setHeader("Content-Disposition","attachment;filename=" + codedfilename);   
		}   
		else if (null != agent && -1 != agent.indexOf("Mozilla"))   
		{       
		String codedfilename = MimeUtility.encodeText(cfrfilename, "utf-8", "B");   
		response.setContentType("application/x-download");   
		response.setHeader("Content-Disposition","attachment;filename=" + codedfilename);   
		}   
		else    
		{   
		response.setContentType("application/x-download");   
		response.setHeader("Content-Disposition","attachment;filename=" + cfrfilename);   
		}
		return cfrfilename;  
	}
	
	/**
	 * 获取客户端的真实ip
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {     
	    String ip = request.getHeader("x-forwarded-for");     
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
	        ip = request.getHeader("Proxy-Client-IP");     
	    }     
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
	        ip = request.getHeader("WL-Proxy-Client-IP");     
	    }     
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
	        ip = request.getRemoteAddr();     
	    }     
	    return ip;     
	}   
	
	
	
	
	

	public static String[] getCSVTCONV() {
		return cSVTCONV;
	}

	public static String[] getCJSPCONV() {
		return cJSPCONV;
	}

	public static int getUNmaxLength() {
		return UNmaxLength;
	}

	public static int getUNminLength() {
		return UNminLength;
	}

	public static int getPSmaxLength() {
		return PSmaxLength;
	}

	public static int getPSminLength() {
		return PSminLength;
	}

	public static String getEmailCode() {
		return emailCode;
	}

	public static String getChineseCode() {
		return chineseCode;
	}
	
}